package top.byteio.common.message.client;

import jakarta.mail.Authenticator;
import jakarta.mail.PasswordAuthentication;
import jakarta.mail.Session;
import jakarta.mail.internet.MimeMessage;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import top.byteio.common.message.pojo.MessagerProperty;

import java.util.Properties;

@NoArgsConstructor
@Slf4j
public class MailMessageHelper implements MessagerHelper<MimeMessage> {

    @Override
    public MimeMessage getHelper(MessagerProperty property) {
        // 2. 设置邮件会话属性
        Properties props = new Properties();
        props.put("mail.smtp.host", property.getEndpoint()); // SMTP服务器地址
        props.put("mail.smtp.port", property.getPort()); // 端口
        props.put("mail.smtp.ssl.enable", property.isEnableSsl());
        props.put("mail.smtp.auth", "true"); // 需要认证
        props.put("mail.smtp.starttls.enable", "true"); // 启用TLS加密

        // 3. 创建认证器（用于登录邮箱）
        Authenticator authenticator = new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(property.getUsername(), property.getSecurityKey());
            }
        };

        // 4. 获取邮件会话
        Session session = Session.getInstance(props, authenticator);

        log.info("初始化邮件客户端: endpoint={}, port={}, username={}, protocol={}",
                property.getEndpoint(), property.getPort(), property.getUsername(), property.getProtocol());
        return new MimeMessage(session);
    }

}
